import base64

import pickle
from django.conf import settings
from django.shortcuts import render
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework.generics import ListAPIView, RetrieveAPIView, \
    CreateAPIView, UpdateAPIView
from random import randint, random
from django_redis import get_redis_connection
from threading import Thread

from itsdangerous import TimedJSONWebSignatureSerializer as TJS
from rest_framework_jwt.views import ObtainJSONWebToken

from carts.utils import merge_cart_cookie_to_redis
from meiduo_mall.libs.yuntongxun.sms import CCP
from celery_tasks.sms_code.tasks import send_sms_code
from users.models import User
from users.serializers import UserSerializers, UserShowSerializers, UserEmailSerializers


# Create your views here.

# 定义一个方法
# def send_sms_code(mobile,sms_code):
#     print(11111)
#     ccp = CCP()
#     ccp.send_template_sms(mobile, [sms_code, '5'], 1)


class SMS_Code_View(APIView):
    def get(self, request, mobile):
        # 1,获取前端数据

        # 2,验证手机号格式
        # 判断前端的请求时间间隔是否在６０ｓ内
        # 建立连接
        conn = get_redis_connection('sms_code')
        flag = conn.get('sms_code_flag_%s' % mobile)
        if flag:
            return Response({'error': '频繁操作'}, status=403)

        # 3,生成短信验证码
        sms_code = '%06d' % randint(0, 999999)
        print('短信验证码是：%s' % sms_code)

        pl = conn.pipeline()

        # 4,保存短信 redis string
        # 建立连接
        pl.setex('sms_code_%s' % mobile, 300, sms_code)
        # 写入一个标志数据
        pl.setex('sms_code_flag_%s' % mobile, 60, 2)
        # 将指令通过管道传递给redis
        pl.execute()

        # 5,发送信息
        # ccp=CCP()
        # ccp.send_template_sms(mobile,[sms_code,'5'],1)
        # 开启线程　线程异步执行发送短信的方法操作
        # t = Thread(target=send_sms_code,kwargs={'mobile':mobile,'sms_code':sms_code})
        # t.start()

        # 使用celery
        send_sms_code.delay(mobile, sms_code)

        # 6,结果返回
        return Response('ok')


class UserNameView(APIView):
    '''
    判断用户名是否存在
    '''

    def get(self, reequest, username):
        count = User.objects.filter(username=username).count()

        return Response(
            {'count': count}
        )


class MobileView(APIView):
    '''
    判断手机号是否存在
    '''

    def get(self, request, mobile):
        count = User.objects.filter(mobile=mobile).count()

        return Response(
            {'count': count}
        )


class UserView(CreateAPIView):
    '''
    注册用户
    '''
    serializer_class = UserSerializers


class UserShowView(RetrieveAPIView):
    '''
    展示用户信息
    '''

    serializer_class = UserShowSerializers
    queryset = User.objects.all()

    # 重写get_object
    def get_object(self):
        return self.request.user


class UserEmailView(UpdateAPIView):
    '''
    保存更新邮箱
    '''
    serializer_class = UserEmailSerializers

    # 重写get_object
    def get_object(self):
        return self.request.user


class UserEmailVifyView(APIView):
    '''
    邮箱验证
    '''

    def get(self, request):
        # 1,获取前段数据
        token = request.query_params.get('token')

        # 2,解密token
        tjs = TJS(settings.SECRET_KEY, 300)
        try:
            data = tjs.loads(token)
        except:
            return Response({'errors': '错误的token'}, status=400)

        # 3,获取解密后的用户密码
        username = data.get('username')

        # 4,根据用户名查询用户对象
        user = User.objects.get(username=username)

        # 5,更新用户的邮箱验证状态
        user.email_active = True
        user.save()

        # 6,返回严正状态
        return Response({'email_active':user.email_active})


class UserLoginView(ObtainJSONWebToken):
    '''
    重写登录方法
    '''

    def post(self, request, *args, **kwargs):
        # 不修改原有登录逻辑
        response = super().post(request,*args,**kwargs)
        #增加合并购物车
        serializer = self.get_serializer(data=request.data)

        if serializer.is_valid():
            # 获取user
            user = serializer.object.get('user') or request.user

            response = merge_cart_cookie_to_redis(request,response,user)

            return response

        return response

